/**
 * 
 */
package neptune.web.client.controller;

import neptune.web.client.services.experiment.ExperimentService;
import neptune.web.client.view.ConsoleManager;

import org.gwtlib.client.table.ContentProvider;
import org.gwtlib.client.table.Row;
import org.gwtlib.client.table.Rows;
import org.gwtlib.client.table.ui.Table;

import com.google.gwt.user.client.rpc.AsyncCallback;

/**
 * @author Roberto Bifulco [info@robertobifulco.it, robertobifulco.it]
 * 
 */
public class ExperimentSummaryViewController implements ContentProvider {

	private Table table;

	/**
	 * @param table
	 */
	public ExperimentSummaryViewController(Table table) {
		this.table = table;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.gwtlib.client.table.ContentProvider#load(int, int, int, boolean)
	 */
	/**
	 * Il metodo ha lo scopo di ottenere informazioni dal server per popolare la
	 * tabella. I parametri passati rappresentano le informazioni necessarie a
	 * recuperare l'insieme di dati richiesto dalla particolare pagina della
	 * tabella visualizzata.
	 * 
	 * 
	 */
	public void load(final int begin, int end, final int sortId,
			final boolean ascending) {
		ConsoleManager.addConsoleMessage(
				"Experiment table data loading started...", false);
		ExperimentService.Util.getInstance().getExperimentsTableData(begin,
				end, sortId, ascending, new AsyncCallback<String[][]>() {

					public void onSuccess(String[][] experiments) {
						table.onSuccess(ExperimentsToRows(experiments, begin,
								sortId, ascending));
						ConsoleManager.addConsoleMessage(
								"Experiments table data loaded", false);
					}

					public void onFailure(Throwable arg0) {
						ConsoleManager.addConsoleMessage(
								"Experiments table data load failed: "
										+ arg0.getMessage(), true);

					}

				});
	}

	private Rows ExperimentsToRows(String[][] experiments, int begin,
			int sortId, boolean ascending) {
		if (experiments == null)
			return new Rows(new Row[] {}, 0, 0, false);

		Row[] rows = new Row[experiments.length];
		for (int i = 0; i < experiments.length; ++i) {
			rows[i] = new Row(i, new Object[] { experiments[i][0],
					experiments[i][1], experiments[i][2], experiments[i][3]});
		}
		return new Rows(rows, begin, sortId, ascending);
	}

}
